import java.util.*;

public class BinaryTree {

    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    /**
     * 手动创建二叉树，创建完成之后，返回根节点
     * @return
     */
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;

        return A;
    }


    public static int i = 0;

    public static TreeNode createTree(String str) {
        TreeNode root = null;
        if(str.charAt(i) != '#') {
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = createTree(str);
            root.right = createTree(str);
        }else{
            i++;
        }
        return root;
    }

    // 前序遍历
    public void preOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    /**
     * 非递归实现前序遍历
     * @param root
     */
    public void preOrderNor(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        if(root == null) {
            return;
        }
        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                System.out.print(cur.val + " ");
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
    }

    List<Character> list = new ArrayList<>();
    public List<Character> preorderTraversal(TreeNode root) {
        if(root == null) {
            return list;
        }
        list.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return list;
    }


    public List<Character> preorderTraversal2(TreeNode root) {
        List<Character> list = new ArrayList<>();
        if(root == null) {
            return list;
        }

        list.add(root.val);

        List<Character> leftList = preorderTraversal2(root.left);
        list.addAll(leftList);

        List<Character> rightList = preorderTraversal2(root.right);
        list.addAll(rightList);

        return list;
    }


    // 中序遍历
    public void inOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }

    /**
     * 非递归实现中序遍历
     * @param root
     */
    public void inOrderNor(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        if(root == null) {
            return;
        }
        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.print(top.val + " ");
            cur = top.right;
        }
    }



    // 后序遍历
    public void postOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");
    }


    /**
     * 非递归实现后序遍历
     * @param root
     */
    public void postOrderNor(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        if(root == null) {
            return;
        }
        TreeNode prev = null;
        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            //右边是否为空  或者  右边是否被打印过  则继续出栈 打印
            if(top.right == null || top.right == prev) {
                System.out.print(top.val+" ");
                stack.pop();
                prev = top;
            }else {
                //没有被打印过 则继续入栈
                cur = top.right;
            }
        }
    }

    public int nodeSize = 0;
    // 获取树中节点的个数
    public void size(TreeNode root) {
        if(root == null) {
            return;
        }
        nodeSize++;
        size(root.left);
        size(root.right);
    }

    public int size2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        return size2(root.left) + size2(root.right)+1;
    }

    public int leafSize = 0;
    // 获取叶子节点的个数
    public void getLeafNodeCount(TreeNode root) {
        if(root == null) {
            return;
        }
        if(root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }

    public int getLeafNodeCount2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left)+
                getLeafNodeCount2(root.right);
    }


    // 获取第K层节点的个数
    public int getKLevelNodeCount(TreeNode root,int k) {
        if(root == null) {
            return 0;
        }
        if(k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left,k-1) +
                getKLevelNodeCount(root.right,k-1);
    }

    // 获取二叉树的高度 时间复杂度O(N)  空间复杂度O(logN)
    public int getHeight(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return Math.max(leftHeight,rightHeight)+1;
    }

    // 获取二叉树的高度
    public int getHeight2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        //int leftHeight = getHeight2(root.left);
        //int rightHeight = getHeight2(root.right);

        //return leftHeight > rightHeight ? leftHeight+1: rightHeight+1;
        return getHeight2(root.left) > getHeight2(root.right) ?
                getHeight2(root.left)+1: getHeight2(root.right)+1;
    }

    // 检测值为value的元素是否存在 时间复杂度O(N)  空间复杂度O(logN)
    public TreeNode find(TreeNode root, int val) {
        if(root == null) {
            return null;
        }
        if(root.val == val) {
            return root;
        }
        TreeNode ret = find(root.left,val);
        if(ret != null) {
            //左树找到了
            return ret;
        }
        ret = find(root.right,val);
        if(ret != null) {
            //右树找到了
            return ret;
        }
        return null;
    }
    //时间复杂度：O(min(m,n))
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p != null && q == null || p == null && q != null) {
            return false;
        }
        //走到这里的情况是什么？ 要么2个都是空 要么要个都不是空
        if( p == null && q == null) {
            return true;
        }
        if(p.val != q.val) {
            return false;
        }
        //走到这里 p != null && q != null  && p.val == q.val
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }


    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null) {
            return false;
        }
        if(isSameTree(root,subRoot)) {
            return true;
        }
        if(isSubtree(root.left,subRoot)) {
            return true;
        }
        if(isSubtree(root.right,subRoot)) {
            return true;
        }
        return false;
    }


    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return root;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    public TreeNode invertTree2(TreeNode root) {
        if(root == null) {
            return root;
        }
        TreeNode leftT = invertTree2(root.left);
        TreeNode rightT = invertTree2(root.right);
        if(leftT == null && rightT == null) {
            return root;
        }
        root.left = rightT;
        root.right = leftT;
        return root;
    }

    /**
     * 时间复杂度：O(N^2)
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }

        int lh = getHeight(root.left);
        int rh = getHeight(root.right);

        return Math.abs(lh-rh) <= 1 &&
                isBalanced(root.left) && isBalanced(root.right);

    }



    public boolean isBalanced2(TreeNode root) {
        if(root == null) {
            return true;
        }
        return getHeight3(root) >= 0;
    }

    public int getHeight3(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftHeight = getHeight3(root.left);
        if(leftHeight < 0) {
            return -1;
        }
        int rightHeight = getHeight3(root.right);
        if(rightHeight < 0) {
            return -1;
        }
        if(/*leftHeight >= 0 && rightHeight >= 0 && */Math.abs(leftHeight-rightHeight) <= 1) {
            return Math.max(leftHeight,rightHeight)+1;
        }else {
            return -1;
        }
    }

    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }

        return isSymmetricChild(root.left,root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        if(leftTree == null && rightTree != null || leftTree != null && rightTree == null) {
            return false;
        }
        if(leftTree == null && rightTree == null) {
            return true;


        }
        if(leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricChild(leftTree.left,rightTree.right) &&
                isSymmetricChild(leftTree.right,rightTree.left);
    }





    //层序遍历
    public void levelOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");
            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }


    public List<List<Character>> levelOrder2(TreeNode root) {
        List<List<Character>> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            //每一层的list
            List<Character> list = new ArrayList<>();
            //通过这个size确定一层有多少个元素
            int size = queue.size();//1
            while (size != 0) {
                TreeNode cur = queue.poll();
                list.add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(list);
        }
        return ret;
    }

    // 判断一棵树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root) {
        if(root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur == null) {
                break;
            }
            queue.offer(cur.left);
            queue.offer(cur.right);
        }

        while (!queue.isEmpty()) {
            TreeNode top = queue.peek();
            if(top != null) {
                return false;
            }
            queue.poll();
        }
        return true;
    }


    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return root;
        }
        if(root == p || root == q) {
            return root;
        }
        TreeNode leftV = lowestCommonAncestor(root.left,p,q);
        TreeNode rightV = lowestCommonAncestor(root.right,p,q);
        if(leftV != null && rightV != null) {
            return root;
        }else if(leftV != null) {
            return leftV;
        }else if(rightV != null) {
            return rightV;
        }
        return null;
    }


    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return root;
        }

        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();

        getPath(root,p,stackP);

        getPath(root,q,stackQ);

        int sizeP = stackP.size();
        int sizeQ = stackQ.size();
        int size = sizeP - sizeQ;

        if(size < 0) {
            //第2个栈中元素多
            size = sizeQ - sizeP;
            //第2个栈 出size个元素
            while(size != 0) {
                stackQ.pop();
                size--;
            }

        }else {
            //第1个栈中元素多
            while(size != 0) {
                stackP.pop();
                size--;
            }
        }

        //代码走到这里 说明 2个栈当中 元素的个数是一样的了
        while (!stackP.isEmpty() && !stackQ.isEmpty()) {
            if(stackP.peek() == stackQ.peek()) {
                return stackP.peek();
            }else {
                stackP.pop();
                stackQ.pop();
            }
        }
        return null;
    }

    /**
     * 找到根节点 到 node节点路径上的所有节点 ，存储到栈当中
     * @param root
     * @param node
     * @param stack
     */
    private boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if(root == null || node == null) {
            return false;
        }
        stack.push(root);
        if(root == node) {
            return true;
        }
        boolean flg = getPath(root.left,node,stack);
        if(flg) {
            return true;
        }
        boolean flg2 = getPath(root.right,node,stack);
        if(flg2) {
            return true;
        }
        stack.pop();
        return false;
    }

    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        if(root == null) {
            return stringBuilder.toString();
        }
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode t,StringBuilder stringBuilder) {
        if(t == null) {
            return;
        }
        stringBuilder.append(t.val);
        //判断当前t的左边
        if(t.left != null) {
            stringBuilder.append("(");
            tree2strChild(t.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if(t.right == null) {
                return;
            }else {
                stringBuilder.append("()");
            }
        }

        //判断当前t的右边
        if(t.right != null) {
            stringBuilder.append("(");
            tree2strChild(t.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }

}

